/**
 * 
 */
package org.mspring.mlog.service.impl;

import java.util.Date;
import java.util.List;

import org.mspring.mlog.entity.Tag;
import org.mspring.mlog.service.TagService;
import org.mspring.platform.persistence.hibernate.BaseHibernateDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Gao Youbo
 * @since 2012-7-24
 * @Description
 * @TODO
 */
@Service
@Transactional
public class TagServiceImpl extends BaseHibernateDao<Tag, java.lang.Long> implements TagService {

    /*
     * (non-Javadoc)
     * 
     * @see org.mspring.mlog.service.TagService#findLikeByName(java.lang.String)
     */
    @Override
    public List<Tag> findLikeByName(String name) {
        // TODO Auto-generated method stub
        String queryString = "select tag from Tag tag where tag.name like ?";
        return list(queryString, name + "%");
    }

    @Override
    public Tag findUniqueByName(String name) {
        // TODO Auto-generated method stub
        return uniqueResult("select tag from Tag tag where tag.name = ?", name);
    }

    public boolean checkTagNameExists(String name, Long id) {
        // System.out.println(name+""+id);
        int count = 0;
        if (id == null) {
            count = getHibernateTemplate().count("select count(*) from Tag tag where tag.name = ?", name);
        } else {
            count = getHibernateTemplate().count("select count(*) from Tag tag where tag.name = ? and tag.id <> ?", new Object[] { name, id });
        }
        // System.out.println(count);
        return count > 0;
    }

    public void updateTag(Tag tag) {
        if (tag.getCreateTime() == null) {
            tag.setCreateTime(new Date());
        }
        update(tag);
    }

}
